/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var NN = require('../Poker/NN');
var PokerRoom = require('../Poker/room').PokerRoom;

var Const = require('./const');
var SubCode = require('../subCode');

var RoundStatus = {
    'WAITING': 1,   // 等待其它玩家准备
    'PREPARE': 2,   // 准备人数足够，将继续等待，其它玩家依然可以准备
    'READY': 3,     // 就绪，开始游戏
    'PLAY': 4,     // 玩家选牌
}

exports.HSNNRoom = PokerRoom.extend({
    _roundStatus: RoundStatus.WAITING,

    _dealerIndex: 0,           // 庄家坐位
    _selectWaitTime: 0,        // 开始选牌的时间

    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);

        this.baseScore = parseInt(this.getOption("baseScore"));
        this.specialCard = this.getOption("specialCard");
        this.selected = false;
        this.robDealered = false;
        this.MS = this.getOption("MS") == 1 ? "NNSZ" : "KPQZ";
        this._roundStatus = RoundStatus.WAITING;
        this._dealerIndex = 0;
        // if (this.getOption("MS") == "FZZ") {
        //     this._dealerIndex = 1;
        // } else {
        //     this._dealerIndex = 0;
        // }

        this._selectWaitTime = 0;
    },
    reset: function () {
        this.selected = false;
        this.robDealered = false;
    },
    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function () {
        var info = this._super();
        info.robDealerWaitMS = this.getHideOption("robDealerWaitMS");
        info.selectWaitMS = this.getHideOption("selectWaitMS");
        info.selected = this.selected;
        info.robDealered = this.robDealered;

        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.dealer = this._dealerIndex;
        info.selectWaitTime = this._selectWaitTime;
        info.selected = this.selected;
        info.robDealered = this.robDealered;
        return info;
    },

    onAfterPlayerReady: function (player) {
        this._super(player);

        var subConfig = this.getSubConfig();

        console.log("AFterplayreadydddd")
        console.log(this.isPlaying())
        console.log(this.getReadyPlayerCount())
        console.log(this.getPlayerCount())
        
        
        if (!this.isPlaying() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin && this.getPlayerCount() == this.getReadyPlayerCount()) {
            var enableStart = false;
            if (this.isSceneRoom()) {
                enableStart = true;
            } else if (this.isCardRoom()) {
                var creator = this.getPlayerByUid(this.getCreator());
                enableStart = (creator && creator.isReady()) ? true : false;
            }

            if (enableStart) {
                this._startNewRoundAfter(this.getHideOption("startWaitMS"));
            }
        }
    },

    // onPlayerQuitRoom: function (player) {
    //     this._super(player);

    //     if (this._roundStatus != RoundStatus.PREPARE) {
    //         return;
    //     }

    //     if (this.getReadyPlayerCount() <= this.getSubConfig().roomPlayerMin) {
    //         this.broadcast("onCancelStartWait", {});
    //         this._roundStatus = RoundStatus.WAITING;
    //     }
    // },


    checkStartNewRound: function () {
        if (this.isPlaying()) {
            return false;
        }

        if (this._roundStatus != RoundStatus.READY) {
            return false;
        }

        return true;
    },

    onBeforeStartNewRound: function () {
        this._super();
        this._selectWaitTime = 0;
        console.log('onbeffff')
        console.log(this.MS);
        if (this.MS == "NNSZ") {
            if (this._dealerIndex == 0) {
                console.log("set dealll;")
                var nums = this.getReadyPlayerCount();
                console.log(nums);
                var dealIndex = Math.floor(Math.random() * nums) + 1;
                var validIndex = 0
                for (var i = 0; i < dealIndex; ++i) {
                    validIndex = this.getNextPlayer(validIndex);
                }
                
                console.log(validIndex);

                this._dealerIndex = validIndex;
                var randoms = [];

                this.enumPlayers(function(eIndex,ePlayer){
                    randoms.push(eIndex);
                })


                this.broadcastReplay("onDealerChanged", {
                    dealer: this._dealerIndex,
                    random: randoms,
                });
            }
        }

    },

    onAfterStartNewRound: function () {
        this._super();
        if (this.MS != "NNSZ") {
            this._startPlay();
        }
    },

    onSettlement: function () {
        this._super();

        this.enumPlaying(function (eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });
    },

    onCurRoundFinished: function () {
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        //最小方块A
        if (this.MS == "NNSZ") {
            var maxNiu = {
                "index": this._dealerIndex,
                "maxNum": 301
            }
            var Nius = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (ePlayer._stat.roundPattern == Const.Pattern.NN) {
                    Nius.push(eIndex);
                    if (NN.cardLT(ePlayer._getMaxCard(), maxNiu["maxNum"])) {
                        maxNiu["maxNum"] = ePlayer._getMaxCard();
                        maxNiu["index"] = eIndex;
                    }
                }
            });

            this._dealerIndex = maxNiu["index"];
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
                random: Nius,
            });
        }
        this.reset();
    },

    /******************************************************************
     * 功能接口
     ******************************************************************/

    handleRobDealer: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.MS != "KPQZ") {
            callback({ code: SubCode.QZNN_MS_UNMATCH }); return;
        }

        if (player.getRobDealer() != -1) {
            callback({ code: SubCode.QZNN_ROB_DEALER_SET }); return;
        }

        if (!msg.hasOwnProperty('value') || isNaN(msg.value)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        var value = parseInt(msg.value);
        if (value != 0 && value != 1 && value != 2 && value != 3 && value != 4) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        console.log("sfads");
        console.log(player.getIndex());
        player.setRotDealer(value);
        this.broadcast("onPlayerRobDealer", {
            playerIndex: player.getIndex(),
            value: value
        });
        callback({});

        var isAllSet = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (ePlayer.getRobDealer() == -1) {
                isAllSet = false;
            }
        });

        if (isAllSet) {
            this.robDealered = true;
            this._dealRobDealerAllSet();
        }
    },
    handleSelectMulti: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.MS != "NNSZ") {
            callback({ code: SubCode.QZNN_MS_UNMATCH }); return;
        }

        if (player.getRobDealer() != -1) {
            callback({ code: SubCode.QZNN_ROB_DEALER_SET }); return;
        }

        if (!msg.hasOwnProperty('value') || isNaN(msg.value)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        var value = parseInt(msg.value);
        if (value != 0 && value != 1 && value != 2 && value != 3 && value != 4) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        console.log("Mutitititi");
        console.log(player.getIndex());
        player.setRotDealer(value);
        this.broadcast("onPlayerRobDealer", {
            playerIndex: player.getIndex(),
            value: value
        });
        callback({});

        var isAllSet = true;
        this.getPlayerByIndex(this._dealerIndex).setRotDealer(1);
        this.enumPlaying(function (eIndex, ePlayer) {
            if (ePlayer.getRobDealer() == -1) {
                isAllSet = false;
                console.log(ePlayer.getRobDealer());
            }
        });

        if (isAllSet) {
            this.robDealered = true;
            this._startPlay();
            //this._dealRobDealerAllSet();
        }
    },

    handleSelectCards: function (player, msg, callback) {
        if (!msg.cards) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        if (!player.isPlaying()) {
            callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        }

        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.isCurRoundFinished()) {
            callback({ code: Code.ROOM_ROUND_FINISHED }); return;
        }

        var cards = msg.cards;
        if (!ExObject.isArray(cards)) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        if (cards.length == 0) {
            player.setSelectedCards(cards);
        } else {
            if (!player.setSelectedCards(cards)) {
                callback({ code: SubCode.CARD_NOT_EXIST }); return;
            }
        }


        callback({});

        this.broadcast("onPlayerSelectCards", {
            playerIndex: player.getIndex(),
            selectNum: msg.cards.length
        });

        var isAllSelected = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isSelectedCards()) {
                isAllSelected = false;
            }
        });

        if (isAllSelected) {
            this.selected = true;
            this.settlementCurRound(500);
        }
    },

    _startNewRoundAfter: function (timeMS) {
        if (this._roundStatus != RoundStatus.WAITING) {
            return;
        }

        this.broadcast("onRoomStartAfter", {
            time: timeMS,
        });

        this._roundStatus = RoundStatus.PREPARE;

        setTimeout(function () {
            if (this._roundStatus != RoundStatus.PREPARE) {
                return;
            }

            this._roundStatus = RoundStatus.READY;
            this.tryStartNewRound();
        }.bind(this), timeMS);
    },

    _startPlay: function () {
        this.initPlayersHandCards();
        if (this.MS != "KPQZ") {
            //this._waitSelectCards();
        } else {
            //this._waitRobDealer();
        }
    },

    _waitRobDealer: function () {
        setTimeout(function () {
            if (!this.isPlaying()) {
                return;
            }

            if (this._roundStatus != RoundStatus.READY) {
                return;
            }

            this.enumPlaying(function (eIndex, ePlayer) {
                if (ePlayer.getRobDealer() == -1) {
                    ePlayer.setRotDealer(0);
                    this.broadcast("onPlayerRobDealer", {
                        playerIndex: ePlayer.getIndex(),
                        value: 0
                    });
                }
            }.bind(this));

            this._dealRobDealerAllSet();

        }.bind(this), this.getHideOption("robDealerWaitMS"));
    },

    _dealRobDealerAllSet: function () {
        var arr0 = [];
        var arr1 = [];

        this.enumPlaying(function (eIndex, ePlayer) {
            if (ePlayer.getRobDealer()) {
                arr1.push({
                    "index": eIndex,
                    "value": ePlayer.getRobDealer()
                });
            } else {
                arr0.push(eIndex);
            }
        });
        var randoms = []
        if (arr1.length == 0) {
            this._dealerIndex = Ext.randArray(arr0);
            randoms = arr0.slice();
        } else {
            arr1.sort(function (a, b) {
                return a.value < b.value;
            });
            console.log(arr1);
            var dealerArray = [arr1[0]];
            console.log("delarearar");
            console.log(dealerArray);
            for (var i = 1; i < arr1.length; ++i) {
                if (arr1[i].value == arr1[0].value) {
                    dealerArray.push(arr1[i]);
                }
            }
            console.log(dealerArray);
            randoms = dealerArray.map(function (v) {
                return v["index"];
            });
            console.log(randoms);
            if (dealerArray.length == 1) {
                this._dealerIndex = dealerArray[0]["index"];
                randoms = [];
            } else {
                console.log("in");
                this._dealerIndex = Ext.randArray(dealerArray)["index"];
            }
        }

        //this._dealerIndex = Ext.randArray(arr1) || Ext.randArray(arr0);

        this.broadcastReplay("onDealerChanged", {
            dealer: this._dealerIndex,
            random: randoms,
            value: this.getPlayerByIndex(this._dealerIndex).getRobDealer()
        });

        //this._waitSelectCards();
    },

    _waitSelectCards: function () {
        this._roundStatus = RoundStatus.PLAY;
        this._selectWaitTime = Date.getStamp();

        setTimeout(function () {
            this.settlementCurRound();
        }.bind(this), this.getHideOption("selectWaitMS"));
    }
});